package command

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/mix-go/xcli"
	"hy_808/configor"
	"hy_808/di"
	"hy_808/route"
	"hy_808/service"
	"net/http"
	"os"
	"os/signal"
	"strconv"
	"strings"
	"syscall"
	"time"
)

type APICommand struct {
}

func (t *APICommand) Main() {
	//logger
	logger := di.Logdot()
	//server
	server := &http.Server{}
	gin.SetMode(gin.ReleaseMode)
	router := gin.New()
	route.SetRoutes(router)

	server.Addr = ":" + strconv.Itoa(configor.ConfigGlobal.HttpPort)
	server.Handler = router

	// signal
	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		<-ch
		logger.Info("Server shutdown")
		ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
		if err := server.Shutdown(ctx); err != nil {
			logger.Errorf("Server shutdown error: %s", err)
		}
	}()

	fmt.Println(fmt.Sprintf("Server      Name:      %s", xcli.App().Name))
	fmt.Println(fmt.Sprintf("Listen      Addr:      %s", server.Addr))
	fmt.Println(fmt.Sprintf("Framework   Version:   %s", xcli.App().Version))
	fmt.Println(fmt.Sprintf("Process     PID:	%d", os.Getpid()))
	var m = make(map[string]any)
	m["程序"] = xcli.App().Name
	m["版本"] = xcli.App().Version
	m["PID"] = os.Getpid()
	b, _ := json.Marshal(m)
	logger.SpecialLogger("program").Print(string(b))
	/*启动一些全局服务*/
	service.GetBusInfo()
	go service.StartClientJoinHY()
	if err := server.ListenAndServe(); err != nil && !strings.Contains(err.Error(), "http: Server closed") {
		panic(err)
	}

}
